package com.atguigu.gulimail.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimail.product.service.CategoryBrandRelationService;
import com.atguigu.gulimail.product.vo.Catalog2Vo;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimail.product.dao.CategoryDao;
import com.atguigu.gulimail.product.entity.CategoryEntity;
import com.atguigu.gulimail.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
//@Autowired
//CategoryDao categoryDao;
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redisson;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> level1 = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu)->{menu.setChildren(getChildrens(menu,entities));return menu;
        }).sorted((menu1,menu2)->{return (menu1.getSort()==null?0:menu1.getSort())-
                (menu2.getSort()==null?0:menu2.getSort());})
                .collect(Collectors.toList());
        return level1;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单，是否被别的地方引用
        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return  parentPath.toArray(new Long[parentPath.size()]);
    }
//级联更新所有关联的数据
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }
    @Cacheable(cacheNames = {"category"},key = "#root.method.name")
    @Override
    public List<CategoryEntity> getLevel1Categorys() {

        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }
    //todo  产生堆外内存溢出  OutOfDirectMemoryError
    //1.springboot2.0以后默认使用lettuce作为操作redis的客户端。他使用netty进行网络通信
    //2.lettuce的bug导致netty堆外内存溢出    -Xmx300m: netty如果没有指定堆外内存，默认使用-Xmx300m
    // 可以通过-Dio.netty.maxDirectMemory进行设置
    @Override
    public Map<String, List<Catalog2Vo>> getCatalogJson() {
        //给缓存中放json字符串，拿出的json字符串，还用逆转为能用的对象类型【序列化与反序列化】
        //1.加入缓存逻辑
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)){
            //2.缓存中没有，查询数据库
            Map<String, List<Catalog2Vo>> catalogJsonFromDb = getCatalogJsonRedisLock();
            //3.查到的数据放入缓存,将对象转为JSON放在缓存中
            String string = JSON.toJSONString(catalogJsonFromDb);
            stringRedisTemplate.opsForValue().set("catalogJSON",string);
            return catalogJsonFromDb;
        }
        //转为我们指定的对象
        Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
        return result;
    }

    //从数据库查询并封装分类数据
    //使用redis的set lock 111 NX 实现分布式锁
    public Map<String, List<Catalog2Vo>> getCatalogJsonRedisLock() {
        //1.占分布式锁 ，去redis中设置值
        String string = UUID.randomUUID().toString();
        //2.防止服务中断 变成死锁 需要给lock设置过期时间并且必须和加锁操作是同步的（原子的）
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", string,300, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("获取分布式锁成功");
            //获取值对比+对比成功删除+原子操作  使用lua脚本
            Map<String, List<Catalog2Vo>> dataFromDb;
           try {
               dataFromDb = getDataFromDb();
           }finally {
               String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
               //删除锁(原子操作)
               Integer lock1 = stringRedisTemplate.execute(new DefaultRedisScript<>(script, Integer.class),
                       Arrays.asList("lock"), string);
           }
//            String lock1 = stringRedisTemplate.opsForValue().get("lock");
//            if (string.equals(lock1)){
//                stringRedisTemplate.delete("lock");
//            }
            return dataFromDb;
        }else {
            //加锁失败
            //休眠一段时间后重试
            //new Thread().sleep(100);
            System.out.println("获取分布式锁失败");
           return getCatalogJsonRedisLock();
        }
    }
    //使用redisson实现分布式锁
    public Map<String, List<Catalog2Vo>> getCatalogJsonRedissonLock() {
        RLock lock = redisson.getLock("catalogJson-lock");
        lock.lock();
        Map<String, List<Catalog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            }finally {
              lock.unlock();
            }
            return dataFromDb;
    }
    //使用synchronized实现本地锁
    public Map<String, List<Catalog2Vo>> getCatalogJsonLocalLock() {
        synchronized (this){
            return getDataFromDb();
        }

    }

    private Map<String, List<Catalog2Vo>> getDataFromDb() {
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });

            return result;
        }


        List<CategoryEntity> selectList = baseMapper.selectList(null);
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0l);
        Map<String, List<Catalog2Vo>> parent_cid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());
            List<Catalog2Vo> collect = null;
            if (categoryEntities != null) {
                collect = categoryEntities.stream().map(l2 -> {
                    Catalog2Vo category2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<CategoryEntity> levelCatalog3 = getParent_cid(selectList, l2.getCatId());
                    if (levelCatalog3 != null) {
                        List<Catalog2Vo.Catalog3Vo> collect1 = levelCatalog3.stream()
                                .map(l3 -> {
                                    Catalog2Vo.Catalog3Vo category3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                    return category3Vo;
                                }).collect(Collectors.toList());
                        category2Vo.setCatalog3List(collect1);
                    }
                    return category2Vo;
                }).collect(Collectors.toList());
            }


            return collect;
        }));

        String string = JSON.toJSONString(parent_cid);
        stringRedisTemplate.opsForValue().set("catalogJSON", string);
        return parent_cid;
    }


    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
        // return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }

    private List<Long> findParentPath(Long catelogId,List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all){
        List<CategoryEntity> c = all.stream().filter((categoryEntity) -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {categoryEntity.setChildren(getChildrens(categoryEntity,all));
        return categoryEntity;
        }).sorted((menu1,menu2)->{return (menu1.getSort()==null?0:menu1.getSort())-
                        (menu2.getSort()==null?0:menu2.getSort());})
                .collect(Collectors.toList());
        return c;

    }
}